namespace Velocity4Net.Runtime.Parse.AST
{
    /// <summary> Please look at the Parser.jjt file which is
    /// what controls the generation of this class.
    /// *
    /// </summary>
    /// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
    /// </author>
    /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
    /// </author>
    /// <version> $Id: ASTIfStatement.cs,v 1.3 2003/10/27 13:54:10 corts Exp $
    /// </version>
    using System;
    using Velocity4Net.Runtime.Parse;
    using MethodInvocationException = Velocity4Net.Errors.MethodInvocationException;
    using ParseErrorException = Velocity4Net.Errors.ParseErrorException;
    using ResourceNotFoundException = Velocity4Net.Errors.ResourceNotFoundException;
    using InternalContextAdapter = Velocity4Net.Ctx.InternalContextAdapter;
    using System.IO;

    public class ASTIfStatement : SimpleNode
    {
        public ASTIfStatement(int id) : base(id) { }

        public ASTIfStatement(Parser p, int id) : base(p, id) { }

        /**
     * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
     */
        public override bool Render(InternalContextAdapter context, TextWriter writer)
        {
            /*
             * Check if the #if(expression) construct evaluates to true:
             * if so render and leave immediately because there
             * is nothing left to do!
             */
            if (jjtGetChild(0).Evaluate(context))
            {
                jjtGetChild(1).Render(context, writer);
                return true;
            }

            int totalNodes = jjtGetNumChildren();

            /*
             * Now check the remaining nodes left in the
             * if construct. The nodes are either elseif
             *  nodes or else nodes. Each of these node
             * types knows how to evaluate themselves. If
             * a node evaluates to true then the node will
             * render itself and this method will return
             * as there is nothing left to do.
             */
            for (int i = 2; i < totalNodes; i++)
            {
                if (jjtGetChild(i).Evaluate(context))
                {
                    jjtGetChild(i).Render(context, writer);
                    return true;
                }
            }

            /*
             * This is reached when an ASTIfStatement
             * consists of an if/elseif sequence where
             * none of the nodes evaluate to true.
             */
            return true;
        }
    }

}